import { defineStore } from 'pinia'
import {ref,computed} from 'vue'
export const useCounterStore = defineStore('counter', () => {
    // const count = ref(0)
    // const doubleCount = computed(() => count.value * 2)
    // function increment() {
    //   count.value++
    // }
  
    // return { count, doubleCount, increment }
    // 购物车列表
    const cartlist=ref([])
    const myorderList=ref([])
    
    // 购物车商品总数量
const totalCount=computed(()=>{
    let res=0
    cartlist.value.forEach(item=>{
        res+=item.count
    })
    return res
})
const orderList=computed(()=>{
    return cartlist.value.filter(item=>item.checked==true)
})
// 购物车商品总价格
const tatalPrice=computed(()=>{
    let res=0
    cartlist.value.forEach(item=>{
        if(item.checked==true){
            res+=item.count*item.price
        }
    })
    return res.toFixed(2)
})


   const addItem=(payload)=>{
    const index=cartlist.value.findIndex(item=>item.id==payload.id)
    if(index>-1){
        cartlist.value[index].count++
    }else{
        cartlist.value.push({
            ...payload,
            count:1,
            checked:false
        })
    }
   }
//    删除购物车商品
const deleteItem=(id)=>{
    cartlist.value=cartlist.value.filter(item=>item.id!=id)
}
// 加入到订单列表
const addmyOrder=(payload)=>{
    myorderList.value.push(payload)
}
const updataOrderStatus=(id)=>{
    myorderList.value.find(item=>item.id==id).status=2
}
   return{cartlist,myorderList,addItem,deleteItem,totalCount,tatalPrice,orderList,addmyOrder,updataOrderStatus}
  },{
    persist:true
  })